package com;

import com.pojo.Customer;
import com.pojo.Employee;
import com.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import util.MybatisUtils;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class MyBatisTest {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    @Before
    public void init(){
        String resource = "mybatis-config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
            sqlSession = sqlMapper.openSession();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    @Test
    public void findAllStudentTest(){
        List<Student> students = sqlSession.selectList("findAllStudent");
        for (Student student : students) {
            System.out.println(student);
        }
    }
    @After
    public void destory(){
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void findCustomerByNameAndJdbcTest(){
        SqlSession sqlSession = MybatisUtils.getSession();
        Customer customer = new Customer();
        customer.setUsername("jack");
        customer.setJdbc("teacher");
        List<Customer> customers = sqlSession.
                selectList("com.mapper.CustomerMapper.findCustomerByNameAndJobs", customer);
        for (Customer customer1 : customers) {
            System.out.println(customer1.toString());
        }
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void UpdateCustomerTest(){
        SqlSession sqlSession = MybatisUtils.getSession();
        Customer customer = new Customer();
        customer.setId(1);
        customer.setUsername("sb");
        customer.setJdbc("dsb");
        customer.setPhone("18122233");
        int c = sqlSession.update("com.mapper.CustomerMapper.insert", customer);
        System.out.println(c);
        sqlSession.commit();
        sqlSession.close();
    }
}